<template>
  <div id="app">
   <el-card>
     <el-header>
       <span>记事本Book</span>
       <el-button style="float: right; padding: 3px 0" type="text"  @click="add">添加</el-button>
     </el-header>
     <el-input type="text" v-model="input" placeholder="请输入内容" @change="add"></el-input>
     <el-table
         :data="list"
         height="250"
         border
         style="width: 100%">
       <el-table-column
           prop="id"
           label="序号"
           width="180">
         <template  slot-scope="scope">
           {{scope.$index + 1}}
         </template>
       </el-table-column>
       <el-table-column
           prop="event"
           label="事件">
       </el-table-column>
       <el-table-column
           prop="control"
           label="操作"
           width="180">
         <template  slot-scope="scope">
         <el-button
             size="mini"
             type="danger"
             @click="handleDelete(scope.$index, scope.row)">删除</el-button>
         </template>
       </el-table-column>
     </el-table>
     <el-button style="float: right; padding: 3px 0; height: 30px" type="text" @click="remove">清空</el-button>
   </el-card>
  </div>
</template>

<script>
import {nanoid} from 'nanoid'

export default {
  name: "App",
  data(){
    return{
      input:'',
      list:[
        {id:'1',event:'起床',control:''}
      ]
    }
  },
  mounted() {
    // 判断数组是否为空
    if (JSON.parse(window.localStorage.getItem('memory')).length !== 0){
     this.list = JSON.parse(window.localStorage.getItem('memory'))
    }
  },
  methods:{
    // 将数据存储到本地
    memoryInfo(){
      window.localStorage.setItem('memory',JSON.stringify(this.list))
    },
    // 添加数据
    add(){
      console.log('触发了 add 事件!')
      if(this.input === '') return alert('请输入内容!')
      const obj = {
        id: nanoid(),
        event: this.input,
      }
      this.list.push(obj)
      // 添加后并存储数据
      this.memoryInfo(obj)
      this.input = ''
    },
    // 删除数据
    handleDelete(id,row) {
      console.log(id, row)
      this.list.splice(id,1)
      // 清除存储里对应的数据
      window.localStorage.setItem('memory',JSON.stringify(this.list));
    },
    // 清除所有数据
    remove(){
      this.list = undefined
      this.list = new Array()
      // 清除存储里的所有数据
      window.localStorage.clear()
    }

  }
}
</script>

<style scoped>
/*.el-header, .el-footer {*/
/*  background-color: dodgerblue;*/
/*  color: #333;*/
/*  text-align: center;*/
/*  line-height: 60px;*/
/*}*/
/*.el-main {*/
/*  background-color: aqua;*/
/*  color: #333;*/
/*  text-align: center;*/
/*  line-height: 300px;*/
/*}*/

</style>